import api from './Api.js'

/**
 * @description 定义app支付类
 */
export default class AppPay {
	constructor(arg) {
		// 支付方式定义为微信，后续可扩展
		this.provider = 'wxpay'
	}

	/**
	 * @description 发起微信支付
	 * @param {Object} payData 支付参数
	 */
	wxPay(payData = {}) {
		return new Promise((resolve, reject) => {
			uni.showLoading({
				title: '购买中...',
				mask: true
			})

			try {
				api.creatWeChatOrderAPI(payData).then(res => {
					let payResData = {
						...res.data
					}
					delete payResData.out_trade_no

					uni.hideLoading()
					uni.requestPayment({
						provider: this.provider,
						orderInfo: res.data,
						success(newRes) {
							// out_trade_no 订单号
							resolve({
								res: newRes,
								orderInfo: res.data.out_trade_no
							})
							uni.showToast({
								title: '购买成功',
								icon: 'success'
							})
						},
						fail(e) {
							let hint = ''
							if (e.errMsg.includes('payment微信:-2')) {
								hint = '取消支付'
							} else {
								hint = '支付失败'
							}
							uni.showToast({
								title: hint,
								icon: 'none'
							})
							console.log("fail", e)
							reject(e)
						},
						complete() {
							uni.hideLoading()
						}
					})
				})
			} catch (e) {
				console.log('catch', e)
				reject(e)
				uni.hideLoading()
			}
		})
	}

}